﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Microsoft.Extensions.Logging;
using RevitCopilot.Services;
using RevitCopilot.ViewModels;
using RevitCopilot.Views;

namespace RevitCopilot.MCPServer;

[Transaction(TransactionMode.Manual)]
public class StartupCommand : IExternalCommand
{
    private readonly ILogger<StartupCommand> logger;
    private static bool isServerRunning = false;
    public StartupCommand()
    {
        logger = Host.GetService<ILogger<StartupCommand>>();
    }

    private static StartUpView? _statusWindow;

    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        try
        {
            // 获取SocketService实例
            var socketService = Host.GetService<SocketService>();
            if (!isServerRunning)
            {
                // 启动Socket服务
                socketService.Start();
                isServerRunning = true;
                logger.LogInformation("Socket服务已启动");

                // 创建并显示非模态状态窗口
                if (_statusWindow == null || !_statusWindow.IsLoaded)
                {
                    var viewModel = new StartUpViewModel(socketService);
                    _statusWindow = new StartUpView
                    {
                        DataContext = viewModel
                    };
                    _statusWindow.Show(); // 非模态显示
                }
                else
                {
                    _statusWindow.Activate(); // 如果窗口已存在，则激活它
                }
            }
            else
            {
                // 停止Socket服务
                socketService.Stop();
                isServerRunning = false;
                logger.LogInformation("Socket服务已停止");

                // 关闭状态窗口
                if (_statusWindow != null && _statusWindow.IsLoaded)
                {
                    _statusWindow.Close();
                    _statusWindow = null;
                }
            }

            return Result.Succeeded;
        }
        catch (System.Exception ex)
        {
            // 处理异常
            message = ex.Message;
            logger.LogError(ex, "StartupCommand执行失败");
            TaskDialog.Show("RevitCopilot", $"执行失败: {ex.Message}");
            return Result.Failed;
        }
    }
}